package observers;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LoggerObserver implements Observer{
    private static LoggerObserver instance;
    private static final String LOG_FILE = "log.txt";
    public static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss");

    private LoggerObserver(){

    }
    public static LoggerObserver getInstance() {
        if (instance == null) {
            instance = new LoggerObserver();
        }
        return instance;
    }

    @Override
    public void update(String message) {
        LocalDateTime currentDateTime = LocalDateTime.now();
        String dateStr = currentDateTime.format(TIMESTAMP_FORMATTER);
        Path p = Paths.get(LOG_FILE);
        try {
            String content = new String(Files.readAllBytes(p));
            if (message == null) {
                content += "session start at " + dateStr + "\n";
            } else {
                if(!message.contains("history")){
                    content += dateStr + " " + message + "\n";
                }
            }
            Files.write(p, content.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void history(int lineNumber) {
        int count = 0;
        try (RandomAccessFile fileRead = new RandomAccessFile(LOG_FILE, "r")) {
            int length = (int) fileRead.length();
            if (lineNumber == -1) {
                lineNumber = length;
            }
            if (length != 0L) {
                int pos = length - 1;
                while (pos > 0) {
                    pos--;
                    //开始读取
                    fileRead.seek(pos);
                    if (fileRead.readByte() == '\n') {
                        System.out.println(fileRead.readLine());
                        count++;
                        if (count == lineNumber) {
                            break;
                        }
                    }
                }
                if (pos == 0) {
                    fileRead.seek(0);
                    System.out.println(fileRead.readLine());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
